'use client';

import React, { useRef, useState } from 'react';
import clsx from 'clsx';

export interface TabItem {
  key: string;
  label: string;
  disabled?: boolean;
  children?: React.ReactNode;
}

export interface TabsProps {
  className?: string;
  activeKey?: string;
  contentClassName?: string;
  /**
   * Type of the tabs.
   * @default 'lift'
   */
  type?: 'border' | 'box' | 'lift';
  /**
   * Size of the tabs.
   * @default 'medium'
   */
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
  items: TabItem[];
  /**
   * 被隐藏时是否销毁 DOM 结构
   * @default false
   */
  destroyOnHidden?: boolean;
  onChange?: (key: string) => void;
}

function TabsNoMemoized(props: TabsProps) {
  const {
    className,
    contentClassName,
    activeKey,
    type = 'lift',
    size = 'medium',
    items,
    destroyOnHidden = false,
    onChange,
  } = props;

  const nameRef = useRef(`tabs-${Math.random().toString(36).slice(2)}`);

  const [innerActiveKey, setInnerActiveKey] = useState(items[0]?.key);

  const finalActiveKey = activeKey || innerActiveKey;

  return (
    <div
      className={clsx(
        'tabs w-full',
        {
          'tabs-box': type === 'box',
          'tabs-lift': type === 'lift',
          'tabs-border': type === 'border',
          'tabs-xs': size === 'xs',
          'tabs-sm': size === 'sm',
          'tabs-md': size === 'md',
          'tabs-lg': size === 'lg',
          'tabs-xl': size === 'xl',
        },
        className
      )}
    >
      {items.map((item) => (
        <React.Fragment key={item.key}>
          <input
            type="radio"
            name={nameRef.current}
            className="tab"
            aria-label={item.label}
            disabled={item.disabled}
            checked={finalActiveKey === item.key}
            onChange={(e) => {
              if (e.target.checked) {
                setInnerActiveKey(item.key);
                onChange?.(item.key);
              }
            }}
          />
          {(destroyOnHidden ? finalActiveKey === item.key : true) && (
            <div
              className={clsx(
                'tab-content bg-base-100 border-base-300 p-6',
                item.disabled && 'tab-disabled',
                contentClassName
              )}
            >
              {item.children}
            </div>
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

export const Tabs = React.memo(TabsNoMemoized);
